package com.lph.health.controller;

import com.lph.health.service.TOrderSettingService;
import com.lph.health.utils.POIUtil;
import com.lph.health.utils.Result;
import com.lph.health.entity.TOrderSetting;
import io.swagger.annotations.Api;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "预约设置")
@RequestMapping("/orderSetting")
public class TOrderSettingController {

    @Autowired
    private TOrderSettingService tOrderSettingService;

    /**
     * Excel文件上传，并解析文件内容保存到数据库
     * @param excelFile
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile){
        try {
            //读取Excel文件数据
            List<String[]> list = POIUtil.readExcel(excelFile); // 使用POI解析表格数据

            if(list.size()>0){
                // 保存数据库
                List<TOrderSetting> orderSettingList = new ArrayList<>();
                for (String[] strings : list) {
                    String orderDate = strings[0];
                    String number = strings[1];
                    // 将字符型数据转回日期类型和数值类型
                    TOrderSetting orderSetting = new TOrderSetting(new Date(orderDate), Integer.parseInt(number));
                    orderSettingList.add(orderSetting);
                }
                tOrderSettingService.add(orderSettingList);
                return Result.success("添加预约设置成功");
            } else {
                return Result.failure("添加预约设置失败，表格无内容");
            }
        } catch (IOException e) {
            // 文件解析失败
            return Result.failure("上传文件失败" + e.getMessage());
        }
    }

    /**
     * 根据年月获取预约设置信息
     * @param date
     * @return
     */
    @PostMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String date){ // date格式为 yyyy-MM
        try {
            List<Map> list = tOrderSettingService.getOrderSettingByMonth(date);
            return Result.success("获取预约设置成功", list);
        } catch (Exception e){
            return Result.failure("获取预约设置失败" + e.getMessage());
        }
    }

    /**
     * 根据年月获取预约设置信息
     * @param orderSetting
     * @return
     */
    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody TOrderSetting orderSetting){ // date格式为 yyyy-MM
        try {
           return tOrderSettingService.editNumberByDate(orderSetting);
        } catch (Exception e){
            return Result.failure("更新预约设置失败" + e.getMessage());
        }
    }
}
